package com.catfacts;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import javax.servlet.http.*;

import org.apache.http.client.ClientProtocolException;
import org.apache.tools.ant.util.Base64Converter;

import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;

@SuppressWarnings("serial")
public class CatFactsSenderServlet extends HttpServlet {
	
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws IOException {

		try {
			Properties p = new Properties();
			Session s = Session.getDefaultInstance(p, null);

			for(Entity e : Datastore.querySubscribers()){
				String email = (String)e.getProperty("email");
				String num = (String)e.getProperty("num");
				Message msg = new MimeMessage(s);
				msg.setFrom(new InternetAddress("noreply@cat-facts-subscription.appspotmail.com", "Cat Facts"));
				msg.addRecipient(Message.RecipientType.TO, new InternetAddress(email, email));
				msg.setSubject("Cat Fact");
				msg.setText("Did you know? \n\n\t"+getRandomFact()+"\n\n Cat Facts");
				Transport.send(msg);
				String fact = getRandomFact();
				if(fact.length() > 150)
					fact = fact.substring(0,150);
				sendSMS(num,fact);
			}

		} catch (Exception e) {
		}
	}

	private static String getRandomFact() {
		List<String> factlist = new ArrayList<String>();
		
		factlist.add("It has been scientifically proven that owning cats is good for our health and can decrease the occurrence of high blood pressure and other illnesses.");

		factlist.add("Stroking a cat can help to relieve stress, and the feel of a purring cat on your lap conveys a strong sense of security and comfort.");

		factlist.add("The ancient Egyptians were the first civilisation to realise the cat's potential as a vermin hunter and tamed cats to protect the corn supplies on which their lives depended.");

		factlist.add("Sir Isaac Newton is not only credited with the laws of gravity but is also credited with inventing the cat flap.");

		factlist.add("A cat has more bones than a human being; humans have 206 and the cat has 230 bones.");

		factlist.add("A cat's hearing is much more sensitive than humans and dogs.");

		factlist.add("The cat's tail is used to maintain balance.");

		factlist.add("Cats see six times better in the dark and at night than humans.");

		factlist.add("Cats eat grass to aid their digestion and to help them get rid of any fur in their stomachs.");

		factlist.add("A healthy cat has a temperature between 38 and 39 degrees Celcius.");

		factlist.add("Cats have the largest eyes of any mammal.");

		factlist.add("The female cat reaches sexual maturity at around 6 to 10 months and the male cat between 9 and 12 months.");

		factlist.add("A female cat will be pregnant for approximately 9 weeks or between 62 and 65 days from conception to delivery. ");

		factlist.add("The average litter of kittens is between 2 - 6 kittens.");

		factlist.add("Ailurophile is the word cat lovers are officially called.");

		factlist.add("Purring does not always indicate that a cat is happy. Cats will also purr loudly when they are distressed or in pain.");

		factlist.add("All cats need taurine in their diet to avoid blindness. Cats must also have fat in their diet as they are unable to produce it on their own.");

		factlist.add("In households in the UK and USA, there are more cats kept as pets than dogs. At least 35% of households with cats have 2 or more cats.");

		factlist.add("When a cats rubs up against you, the cat is marking you with it's scent claiming ownership.");

		factlist.add("About 37% of American homes today have at least 1 cat.");

		factlist.add("Milk can give some cats diarrhea.");

		factlist.add("The average lifespan of an outdoor-only cat is about 3 to 5 years while an indoor-only cat can live 16 years or much longer.");

		factlist.add("On average, a cat will sleep for 16 hours a day.");

		factlist.add("A domestic cat can run at speeds of 30 mph.");

		factlist.add("The life expectancy of cats has nearly doubled over the last fifty years.");

		factlist.add("Blue-eyed, white cats are often prone to deafness.");

		factlist.add("The cat's front paw has 5 toes and the back paws have 4. Cats born with 6 or 7 front toes and extra back toes are called polydactl.");

		factlist.add("An adult cat has 30 teeth, 16 on the top and 14 on the bottom.");

		factlist.add("There are approximately 60,000 hairs per square inch on the back of a cat and about 120,000 per square inch on its underside.");

		factlist.add("Cats and kittens should be acquired in pairs whenever possible as cat families interact best in pairs.");

		factlist.add("In multi-cat households, cats of the opposite sex usually get along better.");

		factlist.add("The first official cat show in the UK was organised at Crystal Palace in 1871.");
		
		return factlist.get((int)Math.round(Math.random()*factlist.size()));
	}
	
	public static void sendSMS(String number, String msg){
        try {
        	URL url = new URL ("https://api.twilio.com/2010-04-01/Accounts/ACb80245f1512e4f2c83a550a469b40b0a/SMS/Messages.Xml");
        	Base64Converter converter = new Base64Converter();
        	String encoding = converter.encode("ACb80245f1512e4f2c83a550a469b40b0a:a852b10fc203462dd38367464ead42b1");
        	

            HttpURLConnection connection = (HttpURLConnection) url.openConnection();
            connection.setRequestMethod("POST");
            connection.setInstanceFollowRedirects(true);
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setRequestProperty("Content-Type","application/x-www-form-urlencoded;charset=UTF-8");
            connection.setRequestProperty("Accept", "*/*");
            connection.setDefaultUseCaches (false);
            connection.setRequestProperty("Authorization", "Basic " + encoding);
            String encodedMsg = URLEncoder.encode(msg,"UTF-8");
            byte[] outputBytes = ("From=%2B12064625899&To=%2B1"+number+"&Body="+encodedMsg).getBytes("UTF-8");
            OutputStream os = connection.getOutputStream();
            os.write(outputBytes);
            os.flush();
            os.close();

            BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));
            String line = br.readLine();
            while(line !=null){System.out.println(line); line = br.readLine();}

            
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			} catch (ClientProtocolException e) {
				e.printStackTrace();
			} catch (ProtocolException e) {
				e.printStackTrace();
			} catch (IOException e) {
				
				e.printStackTrace();
			}
	       
	}
	

}
